<template>
  <div class="app-container  data">
    <el-form :inline="true">
      <el-form-item label="字典名称">
        <el-select v-model="queryParams.dictType" size="small">
          <el-option
            v-for="item in typeOptions"
            :key="item.dictId"
            :label="item.dictName"
            :value="item.dictType"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="字典标签">
        <el-input
          v-model="queryParams.dictLabel"
          placeholder="请输入字典标签"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="queryParams.status" placeholder="数据状态" clearable size="small">
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['system:dict:add']">新增</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="dataList" style="width: 100%;">
      <el-table-column label="字典编码" align="center" prop="dictCode" />
      <el-table-column label="字典标签" align="center" prop="dictLabel" />
      <el-table-column label="字典键值" align="center" prop="dictValue" />
      <el-table-column label="字典排序" align="center" prop="dictSort" />
      <el-table-column label="状态" align="center" prop="status" :formatter="statusFormat" />
      <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:dict:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:dict:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="字典类型">
          <el-input v-model="form.dictType" :disabled="true" />
        </el-form-item>
        <el-form-item label="数据标签" prop="dictLabel">
          <el-input v-model="form.dictLabel" placeholder="请输入数据标签" />
        </el-form-item>
        <el-form-item label="数据键值" prop="dictValue">
          <el-input v-model="form.dictValue" placeholder="请输入数据键值" />
        </el-form-item>
        <el-form-item label="显示排序" prop="dictSort">
          <el-input-number v-model="form.dictSort" controls-position="right" :min="0" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="dict.dictValue"
            >{{dict.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>




        <!--上传图片-->
        <el-form-item label="上传图片">
<!--
            :before-remove="beforeRemove"-->
          <el-upload
            class="upload-demo"
            :action="url"
            :headers="headers"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :on-success="handleImageSuccess"
            multiple
            list-type="picture"
            :limit="1"
            :on-exceed="handleExceed"
            :file-list="fileList">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传图片格式文件</div>
          </el-upload>
        </el-form-item>





        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { listData, getData, delData, addData, updateData } from "@/api/system/dict/data";
  import { listType, getType } from "@/api/system/dict/type";

  import store from '@/store'
  import { upload } from "@/api/system/dict/type";
  import { getToken } from '@/utils/auth'
  import { uploadAvatar } from "@/api/system/user";
  import {VueCropper} from "vue-cropper";
  export default {
    components: { VueCropper },
    data() {
      return {
        fileList:[],
        // 是否显示弹出层
        openhead: false,
        // 弹出层标题
        title: "修改头像",
        options: {
          img: store.getters.avatar, //裁剪图片的地址
          autoCrop: true, // 是否默认生成截图框
          autoCropWidth: 200, // 默认生成截图框宽度
          autoCropHeight: 200, // 默认生成截图框高度
          fixedBox: true // 固定截图框大小 不允许改变
        },
        previews: {},




        // //上传headers
        headers:{
          'Authorization': null
        },
        // options: {
        //   img: store.getters.avatar, //裁剪图片的地址
        //   autoCrop: true, // 是否默认生成截图框
        //   autoCropWidth: 200, // 默认生成截图框宽度
        //   autoCropHeight: 200, // 默认生成截图框高度
        //   fixedBox: true // 固定截图框大小 不允许改变
        // },
        //url  上传接口地址
        url:null,
        //上传图片
        // fileList: [
        //   //{name: 'food.jpeg', url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'}
        // ],
        // 遮罩层
        loading: true,
        // 总条数
        total: 0,
        // 字典表格数据
        dataList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 状态数据字典
        statusOptions: [],
        // 类型数据字典
        typeOptions: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          dictName: undefined,
          dictType: undefined,
          status: undefined
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          dictLabel: [
            { required: true, message: "数据标签不能为空", trigger: "blur" }
          ],
          dictValue: [
            { required: true, message: "数据键值不能为空", trigger: "blur" }
          ],
          dictSort: [
            { required: true, message: "数据顺序不能为空", trigger: "blur" }
          ]
        }
      };
    },
    created() {
      const dictId = this.$route.params && this.$route.params.dictId;
      this.getType(dictId);
      this.getTypeList();
      this.getDicts("sys_normal_disable").then(response => {
        this.statusOptions = response.data;
      });
      this.getUrl()
    },
    methods: {
      handleExceed(files, fileList) {
        this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
      },
      handleImageSuccess(res, file, fileList) {
        console.log(res)
        console.log(file)
        console.log(file.raw)
        console.log(fileList)

        let formData = new FormData();
        formData.append("avatarfile", file.raw);
        console.log(formData);
        uploadAvatar(formData).then(response => {
          console.log(response)
          this.form.url = response.imgUrl
          console.log(this.form.url)
        }).catch(err=>{
          console.log(err)
        });
      },
      handleRemove(file, fileList) {
        this.fileList.length=0
        this.form.url = ''
        console.log( this.form)
        console.log(this.fileList)
        console.log(file, fileList);
      },
      handlePreview(file) {
        console.log(file);
      },
      // 编辑头像
      editCropper() {
        this.openhead = true;
      },
      // 向左旋转
      rotateLeft() {
        this.$refs.cropper.rotateLeft();
      },
      // 向右旋转
      rotateRight() {
        this.$refs.cropper.rotateRight();
      },
      // 图片缩放
      changeScale(num) {
        num = num || 1;
        this.$refs.cropper.changeScale(num);
      },
      // 上传图片
      uploadImg(file) {
        this.$refs.cropper.getCropBlob(data => {
          console.log(data)
          let formData = new FormData();
          formData.append("avatarfile", data);
          console.log(formData);
          //******************************************************************************************
          // upload(formData).then(response => {
          uploadAvatar(formData).then(response => {
            console.log(response)
            //拿到图片地址
            this.form.url = response.imgUrl
            console.log(this.form.url)
            if (response.code === 200) {
              this.openhead = false;
              this.options.img = process.env.VUE_APP_BASE_API + response.imgUrl;
              this.msgSuccess("修改成功");
            } else {
              this.msgError(response.msg);
            }
            this.$refs.cropper.clearCrop();
          }).catch(err=>{
            console.log(err)
          });
        });
      },

      // // //获取图片上传地址
      getUrl(){
        //******************************************************************************
        // let url =   process.env.VUE_APP_BASE_API+'/common/upload'
        let url =   process.env.VUE_APP_BASE_API+'/system/user/profile/avatar'
        console.log(url)
        this.url = url
        this.headers.Authorization ='Bearer ' + getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
      },
      /** 查询字典类型详细 */
      getType(dictId) {
        getType(dictId).then(response => {
          this.queryParams.dictType = response.data.dictType;
          this.getList();
        });
      },
      /** 查询字典类型列表 */
      getTypeList() {
        listType().then(response => {
          this.typeOptions = response.rows;
        });
      },
      /** 查询字典数据列表 */
      getList() {
        this.loading = true;
        listData(this.queryParams).then(response => {
          console.log(response)
          this.dataList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 数据状态字典翻译
      statusFormat(row, column) {
        return this.selectDictLabel(this.statusOptions, row.status);
      },
      // 取消按钮
      cancel() {
        this.openhead = false;
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          dictCode: undefined,
          dictLabel: undefined,
          dictValue: undefined,
          dictSort: 0,
          status: "0",
          remark: undefined,
          url:undefined,
        };
        this.fileList=[]
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加字典图片";
        this.form.dictType = this.queryParams.dictType;
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        getData(row.dictCode).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改字典数据";
          //****************************************************
          // console.log(process.env.VUE_APP_BASE_API);
          // console.log(response.data.url);
          if (!!response.data.url){
            var object = {name:'',url: process.env.VUE_APP_BASE_API+response.data.url}
            console.log(object)
            this.fileList.push(object)
          }
        });
      },
      /** 提交按钮 */
      submitForm: function() {
        //一进入时候  拿到图片
        // this.form.url = this.options.img
        // this.form.url =  this.previews.url
        console.log(this.form)
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.dictCode != undefined) {
              updateData(this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess("修改成功");
                  this.open = false;
                  this.getList();
                } else {
                  this.msgError(response.msg);
                }
              });
            } else {
              addData(this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess("新增成功");
                  this.open = false;
                  this.getList();
                } else {
                  this.msgError(response.msg);
                }
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        this.$confirm('是否确认删除名称为"' + row.dictLabel + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delData(row.dictCode);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
      }
    }
  };
</script>

<style >
  .v-modal{z-index: 2000!important;}
</style>
